<template>
  <el-dialog
    v-model="props.relevanceDialog"
    title="关联备件"
    width="60%"
    :show-close="false"
  >
    <div style="margin: 0 0 15px 0px">
      设备类型：{{ props.relevanceForm?.name }}
    </div>
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      class="demo-ruleForm"
      size="default"
      status-icon
      label-position="top"
    >
      <el-form-item
        label="备件选择"
        style="width: 100%"
        :rules="{ required: true }"
      >
        <div class="shebei-select">
          <div class="shebei-select__tree">
            <el-input v-model="filterText" placeholder="可输入类型进行搜索" />
            <el-tree
              ref="treeRef"
              :data="data"
              :props="defaultProps"
              default-expand-all
              :filter-node-method="filterNode"
              @node-click="partTypeClick"
              class="custom-tree"
            >
              <template #default="{ node, data }">
                <span
                  class="custom-tree-node show-hide"
                  :class="{ active: currentNode.id == data.id }"
                >
                  <span v-if="node.label.length > 8" class="treeLabel">{{
                    node.label
                  }}</span>
                  <span v-else>{{ node.label }}</span>
                </span>
              </template>
            </el-tree>
          </div>
          <div class="shebei-select__table">
            <TableSearch :search="state.search" @search="onSearch" />
            <Table
              ref="tableRef"
              v-bind="state.tableData"
              class="table-demo"
              @pageChange="onTablePageChange"
              @listenClick="listenClick"
            >
            </Table>
          </div>
          <div class="shebei-select__xuanze">
            <div class="xuanze-herder">
              <div>已选择：{{ partNames.length }}个</div>
              <div class="empty" @click="emptyPart">清空</div>
            </div>
            <div class="people">
              <div v-for="item in partNames">
                {{ item }}
              </div>
            </div>
          </div>
        </div>
      </el-form-item>
      <div style="text-align: right">
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          确定
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
      </div>
    </el-form>
  </el-dialog>
</template>
<script setup lang="ts">
import {
  ElForm,
  ElMessage,
  ElMessageBox,
  ElTree,
  FormInstance,
  FormRules
} from 'element-plus'
import { ref, reactive, watch, defineAsyncComponent } from 'vue'
import { partRelevanceApi } from '/@/api/assets'
import { dictionaryList } from '/@/api/publicApi'
const Table = defineAsyncComponent(
  () => import('/@/components/table/index.vue')
)
const TableSearch = defineAsyncComponent(
  () => import('/@/components/table/search.vue')
)
const props = defineProps({
  relevanceDialog: Boolean,
  relevanceForm: Object
})
const emit = defineEmits(['relevance', 'relevanceSubmit'])

const ruleFormRef = ref<FormInstance>()
const ruleForm = ref({
  part: <any>[]
})
interface Tree {
  id: number
  label: string
  children?: Tree[]
  configValue: string
}

const filterText = ref('')
const treeRef = ref<InstanceType<typeof ElTree>>()

const defaultProps = {
  children: 'children',
  label: 'configValue'
}
const data = ref<any>([])
let currentNode = ref({
  id: '',
  configValue: '',
  children: [],
  customizeFlag: 0,
  parentId: ''
})
watch(filterText, (val) => {
  treeRef.value!.filter(val)
})

const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  return data.configValue.includes(value)
}

watch(
  () => props.relevanceDialog,
  () => {
    if (props.relevanceDialog == true) {
      state.tableData.param.deviceType = props.relevanceForm?.id
      currentNode.value = data.value[0]
      state.tableData.param.partType = currentNode.value.id
      // state.tableData.first = false
    }
  }
)

const getPartType = () => {
  dictionaryList({ configType: 'part_type', keyword: '' }).then((res) => {
    if (res.code == 0) {
      data.value = res.data
      state.tableData.param.deviceType = props.relevanceForm?.id
      state.tableData.param.partType = data.value.id
      getTableData()
    }
  })
}

getPartType()

const validatePartNames = (rule: any, value: any, callback: any) => {
  if (partNames.value.length == 0) {
    callback(new Error('备件不能为空'))
  } else {
    callback()
  }
}
const rules = reactive<FormRules>({
  part: [{ required: true }]
})

// 定义变量内容
const tableRef = ref<RefType>()
const state = reactive<TableDemoState>({
  tableData: {
    flash: false, // 刷新表格
    empty: false, // 清空多选
    first: false, // 首次不刷新数据
    // 表头内容（必传，注意格式）
    header: [
      { key: 'partNum', colWidth: '', title: '备件编号', type: 'text' },
      { key: 'partName', colWidth: '', title: '备件名称', type: 'text' }
      // { key: 'image', colWidth: '', width: '70', height: '40', title: '图片描述', type: 'image' },
    ],
    // 配置项（必传）
    config: {
      listApi: '/device/mobile/devicePartRelevance/getPartListByPage',
      listHttp: 'post',
      total: 0, // 列表总数
      loading: true, // loading 加载
      noPage: false, // 是否分页
      isSerialNo: false, // 是否显示表格序号
      isSelection: true, // 是否显示表格多选
      isOperate: false, // 是否显示表格操作栏
      isExtend: false // 是否可以扩展
    },
    // 搜索参数
    param: {
      deviceType: '', // 必传参数，分页的不要传
      partType: '', // 必传参数，分页的不要传
      inventoryFlag: 1
    }
  },
  // 搜索表单，动态生成（传空数组时，将不显示搜索，注意格式）
  search: {
    param: [
      {
        label: '',
        prop: 'keyword',
        placeholder: '可输入备件编号/名称搜索',
        type: 'input'
      }
    ],
    reset: false
  }
})

// 初始化列表数据
const getTableData = () => {
  state.tableData.flash = !state.tableData.flash
  if (state.tableData.param.partType != '') {
    state.tableData.first = true
  }
}
// 搜索点击时表单回调
const onSearch = (data: EmptyObjectType) => {
  state.tableData.param = Object.assign({}, state.tableData.param, { ...data })
  if (state.tableData.param.partType != '') {
    state.tableData.first = true
    state.tableData.flash = !state.tableData.flash
  }
}
// 分页改变时回调
const onTablePageChange = (page: TableDemoPageType) => {
  state.tableData.param.pageNum = page.pageNum
  state.tableData.param.pageSize = page.pageSize
  getTableData()
}

const partTypeClick = (data: any) => {
  currentNode.value = data
  state.tableData.param.partType = data.id
  getTableData()
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (partNames.value.length == 0) {
        ElMessage.warning('备件不能为空')
      } else {
        partRelevanceApi(props.relevanceForm?.id, ruleForm.value.part).then(
          (res) => {
            if (res.code == 0) {
              ElMessage.success('关联成功')
              emptyPart()
              emit('relevanceSubmit')
            }
          }
        )
      }
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  emptyPart()
  emit('relevance')
}

const partNames = ref<any>([])

const onSelectionChange = (val: any) => {
  let arr = <any>[]
  partNames.value = []
  ruleForm.value.part = []
  val.forEach((i: any) => {
    arr.push(i.id)
    let str = i.partNum + '-' + i.partName
    partNames.value.push(str)
    ruleForm.value.part.push(i.id)
  })
}

const emptyPart = () => {
  partNames.value = []
  ruleForm.value.part = []
  state.tableData.empty = true
}
const onSelect = (val: any) => {}

const emptyBack = () => {
  state.tableData.empty = false
}
//定义方法对象 注意定义的方法 必须在上面已经申明 所以建议objFun申明和 listenClick方法 写在页面最下面
const objFun = {
  onSelectionChange: onSelectionChange,
  onSelect: onSelect,
  emptyBack: emptyBack
}
// 监听子级表格  传过来的方法
const listenClick = (name: string, val: any) => {
  objFun[name](val)
}
</script>
<style scoped lang="scss">
.shebei-select {
  display: flex;
  width: 100%;

  &__tree {
    width: 25%;

    .tree {
      border: 1px solid rgba(224, 224, 224, 1);
      margin-top: 16px;
    }
  }

  &__table {
    width: 50%;
    margin: 2px 16px 0 16px;
  }

  &__xuanze {
    width: 25%;
    border: 1px solid rgba(224, 224, 224, 1);
    padding: 10px;

    .xuanze-herder {
      display: flex;
      justify-content: space-between;

      .empty {
        cursor: pointer;
        color: var(--el-color-primary);
      }
    }
  }
}
.custom-tree {
  margin-top: 10px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: var(--el-font-size-base);
  padding-right: 8px;

  .treeLabel {
    width: 180px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.show-hide :nth-child(2) {
  display: none;
}

.show-hide:hover :nth-child(2) {
  display: inline-block !important;
}

.active {
  color: var(--el-color-primary);
}
</style>
